<template>
  <div class="wapper">
    <div @click="show = true" class="value">
      <van-loading v-if="loading">加载中，请稍候...</van-loading>
      <template v-else>{{ valueMirror ? text : "请选择" }}</template>
    </div>

    <van-popup
      v-model="show"
      safe-area-inset-bottom
      close-on-popstate
      position="bottom"
      get-container="body"
      style="height: 50vh"
    >
      <van-empty
        v-if="!loading && list.length < 1"
        :image="require('@/assets/empty.svg')"
        description="暂无数据"
      />

      <tree v-else :list="list" @change="onChange" />
    </van-popup>
  </div>
</template>

<script>
import { Popup, Loading, Empty } from "vant";
import { getDepartmentListByTree } from "@/api/check";
import Tree from "@/components/Tree";
import { to } from "@/utils";

export default {
  name: "DepartmentTree",
  components: {
    [Popup.name]: Popup,
    [Loading.name]: Loading,
    [Empty.name]: Empty,
    [Tree.name]: Tree,
  },
  model: {
    event: "change",
  },
  props: {
    value: {
      type: [String, Number],
      required: true,
    },
  },
  data() {
    return {
      list: [],
      show: false,
      loading: false,
      token: "",
    };
  },
  computed: {
    valueMirror: {
      get: function () {
        return this.value;
      },
      set: function (val) {
        this.$emit("change", val);
      },
    },
    text() {
      const value = this.valueMirror;

      let rText = "";

      const recursiveTree = (array) => {
        array.forEach(({ id, text, children }) => {
          if (value === id) {
            rText = text;
            return false;
          } else if (Array.isArray(children) && children.length) {
            recursiveTree(children);
          }
        });
      };
      recursiveTree(this.list);
      return rText
    },
  },
  methods: {
    onChange({ id }) {
      this.valueMirror = id;
      this.$nextTick(() => (this.show = false));
    },
    async fetchItems() {
      this.loading = true;
      var params = {
        Token: this.token,
      };
      const [err, res] = await to(getDepartmentListByTree(params));
      this.loading = false;
      if (err) return;
      const {
        Result: { rows },
      } = res;
      let temp = {},
        tree = {};
      rows.forEach((item) => {
        temp[item.id] = {
          id: item.id,
          pID: item.pId,
          text: item.name,
        };
      });

      Object.keys(temp).forEach((key) => {
        let item = temp[key];
        let itemParent = temp[item.pID];
        if (itemParent) {
          !Array.isArray(itemParent.children) && (itemParent.children = []);
          itemParent.children.push(item);
        } else {
          tree[item.id] = item;
        }
      });
      this.list = Object.keys(tree).map((key) => tree[key]);
    },
  },
  created() {
    this.token = localStorage.getItem("tokenKey");
    this.fetchItems();
  },
};
</script>

<style lang="less" scoped>
.wapper,
.value {
  width: 100%;
  height: 100%;
  text-align: center;
}
</style>